package com.our.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.our.util.BusinessException;
import com.our.util.Constants;


@Controller
@RequestMapping
public class FileController {
	@RequestMapping("/upload")
	public void upload(PrintWriter out, MultipartHttpServletRequest request)  {
		try {
			MultipartFile file = request.getFile("upload");
			String filename = UUID.randomUUID().toString();
			File newFile = new File(request.getSession().getServletContext().getRealPath("") +Constants.FILE_PATH + filename);
			System.out.println("--------------"+ newFile);
			file.transferTo(newFile);
			
			String callback = request.getParameter("CKEditorFuncNum");   
	        out.println("<script type=\"text/javascript\">");  
	        out.println("window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" + request.getContextPath() + "/show/"+ filename + "','')");   
	        out.println("</script>");
		} catch (Exception e) {
			e.printStackTrace();
			
		}
	}
	
	@RequestMapping("/show/{fileName}")
	public void show(@PathVariable String fileName, HttpServletResponse response,HttpServletRequest request) throws BusinessException {
		File file = new File(request.getSession().getServletContext().getRealPath("")+Constants.FILE_PATH + fileName);
		if (file.exists()) {
			try {
				FileInputStream fis = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = fis.read(b)) != -1) {
					os.write(b, 0, len);
				}
				fis.close();
			} catch (Exception e) {
				throw new BusinessException("E00C08");
			}
		} else {
			throw new BusinessException("E00C07");
		}
	}
	
}
